<!-- 用户管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 用户列表 -->
      <el-col>
        <el-card shadow="hover" class="data-table">
          <div class="data-table__toolbar">
            <div class="data-table__toolbar--actions">
              <el-button
                v-hasPerm="['sys:user:add']"
                type="primary"
                icon="plus"
                @click="handleOpenDialog({})"
              >
                新增
              </el-button>
            </div>
          </div>

          <el-table
            v-loading="loading"
            :data="pageData"
            border
            stripe
            highlight-current-row
            class="data-table__content"
            align="center"
            @selection-change="handleSelectionChange"
          >
            <!-- 自定义空状态 -->
            <template #empty>
              <div style="padding: 60px 0; text-align: center">
                <el-empty description="暂无数据" />
              </div>
            </template>
            <!-- <el-table-column type="selection" width="50" align="center" /> -->
            <el-table-column label="ID" prop="id" width="60" align="center" />
            <el-table-column label="水库名称" prop="name" align="center" />
            <el-table-column label="水库图片" width="140" align="center">
              <template #default="scope">
                <el-image style="width: 100px; height: 100px" :src="scope.row.image" fit="fill" />
              </template>
            </el-table-column>
            <el-table-column label="水库地址" prop="address" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="190" />
            <el-table-column label="操作" fixed="right" width="190">
              <template #default="scope">
                <el-button
                  v-hasPerm="'sys:user:edit'"
                  type="primary"
                  icon="edit"
                  link
                  size="small"
                  @click="handleOpenDialog(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-hasPerm="'sys:user:delete'"
                  type="danger"
                  icon="delete"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.page"
            v-model:limit="queryParams.pageSize"
            @pagination="fetchData"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户表单 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      :size="drawerSize"
      :close-on-click-modal="false"
      @close="handleCloseDialog"
    >
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="头像" prop="image">
          <SingleImageUpload v-model="formData.image" />
        </el-form-item>

        <el-form-item label="用户名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="关键字搜索">
          <div style="width: 100%">
            <div class="search_box">
              <el-select
                v-model="selectedAddress"
                filterable
                remote
                reserve-keyword
                placeholder="请输入地址"
                :remote-method="remoteAddressSearch"
                :loading="searchLoading"
                style="width: 100%"
                @change="handleAddressSelect"
              >
                <el-option
                  v-for="item in addressOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </div>
            <div id="gaode_Map" ref="gaode_Map"></div>
          </div>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请填写地址" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="formData.longitude" disabled placeholder="请填写地址" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="formData.latitude" disabled placeholder="请填写地址" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from "@/store/modules/app-store";
import { DeviceEnum } from "@/enums/settings/device-enum";

import { ref, reactive, watch, onMounted, computed } from "vue";
import ReservoirAPI from "@/api/system/reservoir";
import { useUserStore } from "@/store";
import { ElMessage, ElMessageBox } from "element-plus";
// 引入高德地图相关
import AMapLoader from "@amap/amap-jsapi-loader";

// 设置安全密钥
window._AMapSecurityConfig = {
  securityJsCode: "f5c65b8d8959a6b6b8765e052d107dc2",
};
const userStore = useUserStore();
defineOptions({
  name: "ReservoirList",
  inheritAttrs: false,
});

// 地图相关变量
const selectedAddress = ref("");
const addressOptions = ref<any[]>([]);
const searchLoading = ref(false);
// 地图相关变量
const input = ref("");
const map = ref<any>(null);
// const auto = ref<any>(null);
const placeSearch = ref<any>(null);
const lnglat = ref<any[]>([]);
const markers = ref<any[]>([]);
const position = ref<any>({});
const gaode_Map = ref<HTMLElement>();
const addressCache = ref<Map<string, any>>(new Map());
const appStore = useAppStore();

const userFormRef = ref();

const queryParams = reactive({
  page: 1,
  pageSize: 10,
});

const pageData = ref<any[]>([]);
const total = ref(0);
const loading = ref(false);

const dialog = reactive({
  visible: false,
  title: "新增水库",
});
const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));

const formData = reactive({
  name: "",
  address: "",
  image: "",
  longitude: "",
  latitude: "",
  id: null as number | null,
});

const rules = reactive({
  name: [{ required: true, message: "水库名称不能为空", trigger: "blur" }],
  address: [{ required: true, message: "地址不能为空", trigger: "blur" }],
});

// 选中的用户ID
const selectIds = ref<number[]>([]);
// 当弹窗打开时初始化地图
watch(
  () => dialog.visible,
  (newVal) => {
    if (newVal) {
      // 延迟初始化地图，确保DOM已渲染
      setTimeout(() => {
        initMap();
      }, 100);
    }
  }
);
// 地图初始化
function initMap() {
  let centerLen = [104.065843, 30.657116];
  // 如果有已有坐标，使用已有坐标作为中心点
  if (formData.longitude && formData.latitude) {
      centerLen = [parseFloat(formData.longitude), parseFloat(formData.latitude)];
    }

  AMapLoader.load({
    key: "b7f379b67cd6962e46be2337d681a683", // 申请好的Web端开发者Key
    version: "2.0",
    plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder"],
  })
    .then((AMap: any) => {
      if (!gaode_Map.value) return;

      map.value = new AMap.Map(gaode_Map.value, {
        zoom: 18, // 初始化地图级别
        center: centerLen, // 中心点坐标
        resizeEnable: true,
      });

      // 设置初始标记
      setMarker(centerLen);

      // 初始化搜索功能
      searchMap(AMap);

      // 监听地图点击事件
      map.value.on("click", clickMapHandler);
    })
    .catch((e: any) => {
      console.error("地图初始化失败:", e);
    });
}

// 初始化搜索功能
function searchMap(AMap: any) {
  // 构造地点查询类
  placeSearch.value = new AMap.PlaceSearch({
    map: map.value,
    city: "全国",
    pageSize: 10,
    pageIndex: 1,
  });
}

// 远程地址搜索方法
function remoteAddressSearch(query: string) {
  if (!query.trim()) {
    addressOptions.value = [];
    return;
  }

  // 检查缓存
  if (addressCache.value.has(query)) {
    addressOptions.value = addressCache.value.get(query);
    return;
  }

  searchLoading.value = true;
  addressOptions.value = [];

  // 使用高德地图的PlaceSearch进行搜索
  if (placeSearch.value) {
    placeSearch.value.search(query, (status: string, result: any) => {
      searchLoading.value = false;
      if (status === "complete" && result.poiList && result.poiList.pois.length > 0) {
        const options = result.poiList.pois.map((item: any) => ({
          value: JSON.stringify({
            lng: item.location.lng,
            lat: item.location.lat,
            address: `${item.pname}${item.cityname}${item.adname}${item.address}${item.name}`,
            name: item.name,
            district: item.district,
          }),
          label: `${item.pname}${item.cityname}${item.adname}${item.address}${item.name}`,
        }));
        addressOptions.value = options;
        // 缓存结果
        addressCache.value.set(query, options);
      }
    });
  } else {
    searchLoading.value = false;
  }
}

// 处理地址选择
function handleAddressSelect(value: string) {
  if (!value) return;

  try {
    const addressInfo = JSON.parse(value);
    formData.longitude = addressInfo.lng;
    formData.latitude = addressInfo.lat;
    console.log("选择的地址信息:", addressInfo);
    formData.address = `${addressInfo.address}`;

    // 设置标记和地图中心
    setMarker([addressInfo.lng, addressInfo.lat]);
    if (map.value) {
      map.value.setCenter([addressInfo.lng, addressInfo.lat]);
    }
  } catch (e) {
    console.error("解析地址信息失败:", e);
  }
}

// 点击地图事件获取经纬度，并添加标记
function clickMapHandler(e: any) {
  const info = e.lnglat;
  formData.longitude = info.lng;
  formData.latitude = info.lat;
  lnglat.value = [info.getLng(), info.getLat()];

  setMarker(lnglat.value);

  // 根据经纬度转换成详细地址
  const geocoder = new AMap.Geocoder({
    city: "全国",
  });

  geocoder.getAddress(lnglat.value, function (status: string, result: any) {
    if (status === "complete" && result.regeocode) {
      formData.address = result.regeocode.formattedAddress;
      input.value = formData.address; // 把查询到的地址赋值到输入框
    }
  });

  position.value = {
    longitude: info.getLng(),
    latitude: info.getLat(),
    address: formData.address,
  };
}

// 添加标记
function setMarker(lnglat: any[]) {
  removeMarker();
  if (!map.value) return;

  const marker = new AMap.Marker({
    position: lnglat,
  });

  marker.setMap(map.value);
  markers.value.push(marker);
}

// 删除之前的标记点
function removeMarker() {
  if (map.value && markers.value.length > 0) {
    map.value.remove(markers.value);
    markers.value = [];
  }
}

// 获取数据
async function fetchData() {
  loading.value = true;
  try {
    const data = await ReservoirAPI.list(queryParams);
    console.log(data);
    pageData.value = data.data.records;
    total.value = data.data.total;
  } finally {
    loading.value = false;
  }
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.page = 1;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryParams.page = 1;
  fetchData();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

// 禁用/启用账号功能暂不需要

/**打开弹窗
 * @param id 用户ID
 */
async function handleOpenDialog(item: any) {
  if (item && item.id) {
    dialog.title = "修改水库";
    console.log("编辑水库ID:", item);
    // ReservoirAPI.detail(id).then((data) => {
    //   // console.log(data.data);
    Object.assign(formData, { ...item });
    // });
  } else {
    dialog.title = "新增水库";
  }
  dialog.visible = true;
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  if (userFormRef.value) {
    userFormRef.value.resetFields();
    userFormRef.value.clearValidate();
  }
  formData.id = null;
  Object.assign(formData, {
    name: "",
    address: "",
    image: "",
    longitude: "",
    latitude: "",
  });
  input.value = "";
  removeMarker();
}

// 提交水库表单（防抖）
const handleSubmit = useDebounceFn(() => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        ReservoirAPI.update(formData)
          .then(() => {
            ElMessage.success("修改水库成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        console.log(formData);
        ReservoirAPI.add({
          name: formData.name,
          address: formData.address,
          image: formData.image,
          longitude: formData.longitude,
          latitude: formData.latitude,
        })
          .then(() => {
            ElMessage.success("新增水库成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

/**删除水库
 * @param id  水库ID
 */
function handleDelete(id?: number) {
  ElMessageBox.confirm("确认删除水库?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      ReservoirAPI.delItem(id)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/** 高德地图样式*/
#gaode_Map {
  overflow: hidden;
  width: 100%;
  height: 300px;
  margin: 10px 0;
  border: 1px solid #ebeef5;
}

.search_box {
  margin-bottom: 10px;
}

/**确保输入框样式统一*/
.search_box :deep(.el-input__wrapper) {
  border-radius: 4px;
}
</style>
